package com.yixun.qfbao.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.yixun.qfbao.chuanglan.request.SmsVariableRequest;
import com.yixun.qfbao.chuanglan.response.SmsVariableResponse;
import com.yixun.qfbao.chuanglan.util.ChuangLanSmsUtil;
import com.yixun.qfbao.enums.QfSmsTemplateEnum;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;

@Component
@ConfigurationProperties(prefix = "smsserver")
public class SMSUtil {
	
	private Logger logger = LoggerFactory.getLogger(SMSUtil.class);

	// 短信接口调用地址
	private String smsurl;

	// 用户名
	private String userName;

	// 密码
	private String pwd;

	// 签名
	private String sign;

	// 短信开关
	private String smsSwitch;
	
	//平台
	private String platform;

	//营销号参数 token,mainAccountCode,subAccountCode,qfSmsUrl
	private String token;

	private String mainAccountCode;

	private String subAccountCode;

	private String qfSmsUrl;

	public String getSmsurl() {
		return smsurl;
	}

	public void setSmsurl(String smsurl) {
		this.smsurl = smsurl;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPwd() {
		return pwd;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

	public String getSign() {
		return sign;
	}

	public void setSign(String sign) {
		this.sign = sign;
	}

	public String getSmsSwitch() {
		return smsSwitch;
	}

	public void setSmsSwitch(String smsSwitch) {
		this.smsSwitch = smsSwitch;
	}

	public String getPlatform() {
		return platform;
	}

	public void setPlatform(String platform) {
		this.platform = platform;
	}

	public String getToken() {
		return token;
	}

	public void setToken(String token) {
		this.token = token;
	}

	public String getMainAccountCode() {
		return mainAccountCode;
	}

	public void setMainAccountCode(String mainAccountCode) {
		this.mainAccountCode = mainAccountCode;
	}

	public String getSubAccountCode() {
		return subAccountCode;
	}

	public void setSubAccountCode(String subAccountCode) {
		this.subAccountCode = subAccountCode;
	}

	public String getQfSmsUrl() {
		return qfSmsUrl;
	}

	public void setQfSmsUrl(String qfSmsUrl) {
		this.qfSmsUrl = qfSmsUrl;
	}

	public Map<String, Object> sendMessage(String content, String mobile, String templateId, Map<String, String> smsSettingMap,Map<String,String> qfSmsMap) {
		Map<String, Object> returnMap = new HashMap<>();
		//默认短信发送平台: 巧房
		platform = "1";
		if (null != smsSettingMap) {
			userName = smsSettingMap.get("userName");
			pwd = smsSettingMap.get("pwd");
			sign = smsSettingMap.get("sign");
			smsurl = smsSettingMap.get("smsurl");
			platform = smsSettingMap.get("platform");
		}else if(null != qfSmsMap){
			platform = "3";
		}else {
			userName = "qiaofang";
			pwd = "B867EB4B97AAF31A72701D930FBA";
			sign = "渠道管理";
			smsurl = "http://sms.1xinxi.cn/asmx/smsservice.aspx";
		}
		try {
			logger.info("开始发送短信,短信平台: " + platform);
			if("1".equals(platform)) {
				Map<String, String> params = new HashMap<>();
				params.put("name", userName);
				params.put("pwd", pwd);
				params.put("mobile", mobile);
				params.put("content", content);
				params.put("sign", sign);
				params.put("stime", "");
				params.put("type", "pt");
				params.put("extno", "");
				String result = RequestUtil.buildRequest(smsurl, params, "UTF-8");
				if(StringUtils.isNotBlank(result)){
					String status = result.split(",")[0];
					String orderUuid = result.split(",")[1];
					returnMap.put("sendStatus", true);
					returnMap.put("orderUuid",orderUuid);
					if (!status.equals("0")) {
						returnMap.put("sendStatus", false);
					}
				}else{
					returnMap.put("sendStatus", false);
				}
				returnMap.put("sendRes", result);
				returnMap.put("platform", "1");

			}else if("2".equals(platform)){
				//飞鸽传书
				List<NameValuePair> formparams = new ArrayList<>();
				formparams.add(new BasicNameValuePair("Account", userName));
				formparams.add(new BasicNameValuePair("Pwd", pwd));
				formparams.add(new BasicNameValuePair("Content", content));
				formparams.add(new BasicNameValuePair("Mobile", mobile));
				formparams.add(new BasicNameValuePair("SignId", sign));
				returnMap = feigePost(formparams, smsurl);
			}else if("3".equals(platform)){
				returnMap = doPostQfSms(qfSmsUrl,templateId,mobile,qfSmsMap);
			}else if("4".equals(platform)){
				returnMap = doPostCLSms(smsSettingMap,qfSmsMap, templateId, mobile);
			}
			logger.info("短信发送完成,短信发送结果: " + JSONObject.toJSONString(returnMap));
		} catch (Exception e) {
			logger.error("短信发送失败: {}", e);
			returnMap.put("sendStatus", false);
			returnMap.put("sendRes", JSONObject.toJSONString(e));
		}
		return returnMap;
	}

	/**
	 * 飛鴿傳書短信平臺發送
	 * @param formparams
	 * @param smsUrl
	 * @return
	 * @throws Exception
	 */
	public Map<String, Object> feigePost(List<NameValuePair> formparams, String smsUrl) throws Exception {
		Map<String, Object> returnMap = new HashMap<>();
		CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();
		httpClient.start();
		HttpPost requestPost = new HttpPost(smsUrl);
		requestPost.setEntity(new UrlEncodedFormEntity(formparams, "utf-8"));
		HttpResponse httpResponse = httpClient.execute(requestPost, new FutureCallback<HttpResponse>() {
			public void failed(Exception arg0) {
			}
			public void completed(HttpResponse arg0) {
			}
			public void cancelled() {
			}
		}).get();
		
		InputStream stram = httpResponse.getEntity().getContent();
		BufferedReader reader = new BufferedReader(new InputStreamReader(stram));
		String returnMsg = reader.readLine();
		JSONObject jsonObject = JSONObject.parseObject(returnMsg);
		String code = jsonObject.getString("Code");

		returnMap.put("sendStatus", true);
		if(!"0".equals(code)) {
			returnMap.put("sendStatus", false);
		}
		returnMap.put("sendRes", returnMsg);
		returnMap.put("platform", "2");
		return returnMap;
	}


	/**
	 * 请求营销号短信平台
	 * @param url
	 * @param templateId
	 * @param phone
	 * @param contentMap
	 * @return
	 */
	public  Map<String, Object> doPostQfSms(String url,String templateId,String phone,Map<String,String> contentMap) throws Exception{

		Map<String, Object> returnMap = new HashMap<>();

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("token",token);
		jsonObject.put("mainAccountCode",mainAccountCode);

		jsonObject.put("subAccountCode", subAccountCode);
		jsonObject.put("templateId", templateId);
		JSONArray jsonArray = new JSONArray();
		jsonArray.add(phone);
		jsonObject.put("targets", jsonArray);
		jsonObject.put("templateParas",contentMap);

		String result = null;
		HttpClient client = HttpClientBuilder.create().build();
		HttpPost httpPost;
		httpPost = new HttpPost(url);
		httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
		StringEntity se = new StringEntity(jsonObject.toJSONString(), Charset.forName("UTF-8"));
		se.setContentType("application/json");
		httpPost.setEntity(se);
		HttpResponse response = client.execute(httpPost);
		if (response != null) {
			HttpEntity resEntity = response.getEntity();
			if (resEntity != null) {
				result = EntityUtils.toString(resEntity, "UTF-8");
			}
		}
		JSONObject resultObject = JSONObject.parseObject(result);
		logger.info("巧房短信平台短信发送结果： ", resultObject.toJSONString());
		returnMap.put("sendStatus", true);
		if(resultObject.containsKey("data") && resultObject.getJSONObject("data").containsKey("successMap") && resultObject.getJSONObject("data").getJSONObject("successMap").containsKey(phone)){
			returnMap.put("orderUuid",resultObject.getJSONObject("data").getJSONObject("successMap").get(phone));
		}
		if(!"1".equals(resultObject.get("responseCode"))) {
			returnMap.put("sendStatus", false);
		}
		returnMap.put("sendRes", result);
		returnMap.put("platform", "3");
		return returnMap;
	}

	/**
	 * 请求创蓝短信平台
	 * @param smsSetting
	 * @param qfSmsMap
	 * @param templateId
	 * @param mobile
	 * @return
	 * @throws Exception
	 */
	public  Map<String, Object> doPostCLSms(Map<String, String> smsSetting, Map<String,String> qfSmsMap, String templateId, String mobile) throws Exception{
		Map<String, Object> returnMap = new HashMap<>();

		String charset = "utf-8";
		// 请登录zz.253.com 获取创蓝API账号(非登录账号,示例:N1234567)
		String account = smsSetting.get("userName");
		// 请登录zz.253.com 获取创蓝API密码(非登录密码)
		String pswd = smsSetting.get("pwd");
		//变量短信发送的URL 请登录zz.253.com 获取完整的URL接口信息
		String smsVariableRequestUrl = smsSetting.get("smsurl");
		//设置您要发送的内容：其中“【】”中括号为运营商签名符号，多签名内容前置添加提交
		String msg = "【" + smsSetting.get("sign") + "】" + QfSmsTemplateEnum.getById(templateId).getMsg();
		msg = msg.replaceAll("Param", "\\$var");
		//参数组
		String params = "";
		if(null == qfSmsMap || qfSmsMap.isEmpty()){
			returnMap.put("sendStatus", false);
			returnMap.put("sendRes", "发送内容为空!");
			return returnMap;
		}

		for (String key : qfSmsMap.keySet()) {
			params += qfSmsMap.get(key) + ",";
		}
		params = mobile + "," + params.substring(0, params.length() - 1);

		//状态报告
		String report= "true";
		SmsVariableRequest smsVariableRequest=new SmsVariableRequest(account, pswd, msg, params, report);
		String requestJson = JSON.toJSONString(smsVariableRequest);
		//System.out.println("before request string is: " + requestJson);
		String response = ChuangLanSmsUtil.sendSmsByPost(smsVariableRequestUrl, requestJson);
		//System.out.println("response after request result is : " + response);
		SmsVariableResponse smsVariableResponse = JSON.parseObject(response, SmsVariableResponse.class);
		//System.out.println("response  toString is : " + smsVariableResponse);
		returnMap.put("sendStatus", true);
		if(!"0".equals(smsVariableResponse.getCode())) {
			returnMap.put("sendStatus", false);
		}
		returnMap.put("sendRes", smsVariableResponse.toString());
		returnMap.put("platform", "4");
		return returnMap;
	}

	// 巧房模板短信
	public Map<String, Object> sendQFTempMessage(String mobile, Map<String, String> smsSettingMap, Map<String,String> qfSmsMap) {
		Map<String, Object> returnMap = new HashMap<>();
		try {
			logger.info("开始发送模板短信: {}" + JSONObject.toJSONString(smsSettingMap));
			returnMap = doPostQFTempSms(mobile, smsSettingMap, qfSmsMap);
			logger.info("短信发送完成,短信发送结果: " + JSONObject.toJSONString(returnMap));
		} catch (Exception e) {
			logger.error("短信发送失败: {}", e);
			returnMap.put("sendStatus", false);
			returnMap.put("sendRes", JSONObject.toJSONString(e));
		}
		return returnMap;
	}

	/**
	 * 发送定制短信
	 * @param phone
	 * @param smsSettingMap
	 * @param contentMap
	 * @return
	 * @throws Exception
	 */
	public  Map<String, Object> doPostQFTempSms(String phone, Map<String, String> smsSettingMap, Map<String,String> contentMap) throws Exception{
		Map<String, Object> returnMap = new HashMap<>();
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("token",smsSettingMap.get("sign"));
		jsonObject.put("mainAccountCode", smsSettingMap.get("userName"));
		jsonObject.put("subAccountCode", smsSettingMap.get("subUserName"));
		jsonObject.put("templateId", smsSettingMap.get("tempNo"));
		JSONArray jsonArray = new JSONArray();
		jsonArray.add(phone);
		jsonObject.put("targets", jsonArray);
		jsonObject.put("templateParas",contentMap);

		String result = null;
		HttpClient client = HttpClientBuilder.create().build();
		HttpPost httpPost;
		httpPost = new HttpPost(smsSettingMap.get("smsurl"));
		httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
		StringEntity se = new StringEntity(jsonObject.toJSONString(), Charset.forName("UTF-8"));
		se.setContentType("application/json");
		httpPost.setEntity(se);
		HttpResponse response = client.execute(httpPost);
		if (response != null) {
			HttpEntity resEntity = response.getEntity();
			if (resEntity != null) {
				result = EntityUtils.toString(resEntity, "UTF-8");
			}
		}
		JSONObject resultObject = JSONObject.parseObject(result);
		logger.info("巧房短信平台短信发送结果： ", resultObject.toJSONString());
		returnMap.put("sendStatus", true);
		if(resultObject.containsKey("data") && resultObject.getJSONObject("data").containsKey("successMap") && resultObject.getJSONObject("data").getJSONObject("successMap").containsKey(phone)){
			returnMap.put("orderUuid",resultObject.getJSONObject("data").getJSONObject("successMap").get(phone));
		}
		if(!"1".equals(resultObject.get("responseCode"))) {
			returnMap.put("sendStatus", false);
		}
		returnMap.put("sendRes", result);
		returnMap.put("platform", "3");
		return returnMap;
	}


	public static void main(String[] args) {
		//第一信息

		SMSUtil smsUtil = new SMSUtil();
		/*
		smsUtil.setSmsurl("http://sms.1xinxi.cn/asmx/smsservice.aspx");
		smsUtil.setUserName("keweilitian");
		smsUtil.setPwd("6D1574024E606B3A085D0114CEDD");
		smsUtil.setSign("渠道管理");
		smsUtil.setSmsSwitch("T");
		smsUtil.setPlatform("1");
		 */
		
		/*
		SMSUtil smsUtil = new SMSUtil();
		smsUtil.setSmsurl("http://api.feige.ee/SmsService/Send");
		smsUtil.setUserName("qiaofang88");
		smsUtil.setPwd("2ace4b09c8d51499e0ee3cc2e");
		smsUtil.setSign("44078");
		smsUtil.setSmsSwitch("T");
		smsUtil.setPlatform("2");
		*/


		/**
		 * 创蓝
		 */
//		Map<String, String> smsSettingMap = new HashMap<String, String>();
//		smsSettingMap.put("userName", "N1470376");
//		smsSettingMap.put("pwd", "y85R1zPmnEe001");
//		smsSettingMap.put("smsurl", "http://smssh1.253.com/msg/variable/json");
//		smsSettingMap.put("sign", "巧房渠道管理");
//		smsSettingMap.put("platform", "4");
//
//		Map<String,String> qfSmsMap = new HashMap<>();
//		qfSmsMap.put("key1", "J29dLY1");
//
//		Map<String, Object> returnMap = smsUtil.sendMessage(null, "13764252725","44d942531e964b88a67fcb568a72d9dd", smsSettingMap,qfSmsMap);
//		System.out.println(JSONObject.toJSONString(returnMap));

		JSONObject jsonObject = JSONObject.parseObject("{\"responseCode\":\"1\",\"responseMessage\":\"success\",\"responseType\":null,\"data\":{\"invalidPhoneList\":[],\"failPhoneList\":[],\"successMap\":{\"15136350996\":\"5aef1b3c-9783-4f5e-9044-d24c6d261274_395860700\"}}}");
		JSONObject successMap =  jsonObject.getJSONObject("successMap");
	}
}
